<template>
    <div class="app-container">
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button plain icon="Download" @click="handleImport">导入</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button plain icon="Edit" @click="handleExport">导出</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="primary" @click="handleOut">退出</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="primary" @click="handleSave">保存</el-button>
            </el-col>
        </el-row>

        <el-table v-loading="loading" :data="dataList" border :span-method="objectSpanMethod">
            <el-table-column label="省" align="center" prop="province" />
            <el-table-column label="市" align="center" prop="city" />
            <el-table-column label="区（县）" align="center" prop="prefecture" />
            <el-table-column label="结构类型" align="center" prop="structureType" width="200">
                <template #default="scope">
                    <span v-if="scope.row.structureType == '0'">土木/石木结构</span>
                    <span v-else-if="scope.row.structureType == '1'">砌体结构</span>
                    <span v-else-if="scope.row.structureType == '2'">木结构</span>
                    <span v-else-if="scope.row.structureType == '3'">窑洞</span>
                    <span v-else-if="scope.row.structureType == '4'">钢筋混凝土结构</span>
                    <span v-else-if="scope.row.structureType == '5'">木（竹）结构</span>
                    <span v-else-if="scope.row.structureType == '6'">混杂结构</span>
                    <span v-else-if="scope.row.structureType == '7'">钢结构</span>
                    <span v-else-if="scope.row.structureType == '8'">其他</span>
                    <span v-else-if="scope.row.structureType == '9'">底部框架-抗震墙砌体结构</span>
                </template>
            </el-table-column>

            <el-table-column label="基本完好" align="center" prop="zero"></el-table-column>
            <el-table-column label="轻微破坏" align="center" prop="one"></el-table-column>
            <el-table-column label="中等破坏" align="center" prop="two"></el-table-column>
            <el-table-column label="严重破坏" align="center" prop="three"></el-table-column>
            <el-table-column label="损坏" align="center" prop="four"></el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" prop="province">
                <template #default="scope">
                    <el-button type="text" @click="handleUpdate(scope.row)">修改</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 修改弹出框 -->
        <el-dialog :title="title" v-model="open" append-to-body width="1200px">
            <p class="dialogTitle">{{ title }}</p>
            <el-form ref="destructionRatioRef" :model="form" :rules="rules" style="padding:0 40px 0px 20px">
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="省" prop="province" label-width="150px">{{ form.province }}</el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="市" prop="city" label-width="150px">{{ form.city }}</el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="区（县）" prop="prefecture" label-width="150px">{{ form.prefecture }}
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-table :data="form.dataDetailList" border class="borderTable">
                    <el-table-column label="结构类型" align="center" prop="structureType" width="200">
                        <template #default="scope">
                            <span v-if="scope.row.structureType == '0'">土木/石木结构</span>
                            <span v-else-if="scope.row.structureType == '1'">砌体结构</span>
                            <span v-else-if="scope.row.structureType == '2'">木结构</span>
                            <span v-else-if="scope.row.structureType == '3'">窑洞</span>
                            <span v-else-if="scope.row.structureType == '4'">钢筋混凝土结构</span>
                            <span v-else-if="scope.row.structureType == '5'">木（竹）结构</span>
                            <span v-else-if="scope.row.structureType == '6'">混杂结构</span>
                            <span v-else-if="scope.row.structureType == '7'">钢结构</span>
                            <span v-else-if="scope.row.structureType == '8'">其他</span>
                            <span v-else-if="scope.row.structureType == '9'">底部框架-抗震墙砌体结构</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="基本完好" align="center" prop="zero">
                        <template #default="scope">
                            <el-form-item :prop="'dataDetailList.' + scope.$index + '.zero'" :rules="rules.zero">
                                <el-input v-model="scope.row.zero" />
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column label="轻微破坏" align="center" prop="one">
                        <template #default="scope">
                            <el-form-item :prop="'dataDetailList.' + scope.$index + '.one'" :rules="rules.one">
                                <el-input v-model="scope.row.one" />
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column label="中等破坏" align="center" prop="two">
                        <template #default="scope">
                            <el-form-item :prop="'dataDetailList.' + scope.$index + '.two'" :rules="rules.two">
                                <el-input v-model="scope.row.two" />
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column label="严重破坏" align="center" prop="three">
                        <template #default="scope">
                            <el-form-item :prop="'dataDetailList.' + scope.$index + '.three'" :rules="rules.three">
                                <el-input v-model="scope.row.three" />
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column label="损坏" align="center" prop="four">
                        <template #default="scope">
                            <el-form-item :prop="'dataDetailList.' + scope.$index + '.four'" :rules="rules.four">
                                <el-input v-model="scope.row.four" />
                            </el-form-item>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确定</el-button>
                    <el-button @click="cancel">取消</el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 导入对话框 -->
        <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body custom-class="dialogTable">
            <p></p>
            <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url" :data="upload.data"
                :disabled="upload.isUploading" :before-upload="handleFileBeforeUpload"
                :on-progress="handleFileUploadProgress" :on-error="handleFileUploadError"
                :on-success="handleFileSuccess" :auto-upload="false" drag>
                <el-icon class="el-icon--upload">
                    <upload-filled />
                </el-icon>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <template #tip>
                    <div class="el-upload__tip text-center">
                        <span>仅允许导入xls、xlsx格式文件。</span>
                        <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                            @click="importTemplate('房屋破坏比率模板.xlsx')">下载模板</el-link>
                    </div>
                </template>
            </el-upload>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitFileForm">确 定</el-button>
                    <el-button @click="upload.open = false">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
  
<script setup>
import { ElMessage } from 'element-plus'
import { getAllbuildingVulnerability, updatebuildingVulnerability, delbuildingVulnerability } from "@/api/assess/destructionRatio.js"
import { getToken } from "@/utils/auth";
import { dataMethod } from '@/utils/spanTable.js'
import useAssessStore from '@/store/modules/assess'
import {storeToRefs} from 'pinia'

const assessStore = useAssessStore()
let { assessId } = storeToRefs(assessStore)
const { proxy } = getCurrentInstance();
const router = useRouter();
const route = useRoute();
const ids = ref();
const dataList = ref([]);
const spanObj = ref();
const spanObjUpdate = ref();
const loading = ref(false);
const open = ref(false);
const title = ref("");
const messageArr = ref([]);
const isUpdate = ref(false);
/*** 用户导入参数 */
const upload = reactive({
    open: false,
    title: "",
    isUploading: false,
    headers: { token: "tokrn " + getToken() },
    url: import.meta.env.VITE_APP_BASE_API + "/fxfzaqbz/DestoryRate/importExcel",
    data:{...route.query}
});

// 保留两位小数
const positive2decimals = (rule, value, callback) => {
    if (value) {
        value = String(value)
    }
    if (!value && typeof value == object) {
        callback(new Error())
    } else if (value.split('.').length > 2) {
        callback(new Error()) //防止输入多个小数点
    } else {
        value = Math.round(value * Math.pow(10, 2)) / Math.pow(10, 2) //四舍五入
        value = Number(value).toFixed(2); //不足补位
        // this.traditionDetails.orderPrice = value;
        if (rule.field.split('.')[2] == 'zero') {
            form.value.dataDetailList[rule.field.split('.')[1]].zero = value;
        } else if (rule.field.split('.')[2] == 'one') {
            form.value.dataDetailList[rule.field.split('.')[1]].one = value;
        } else if (rule.field.split('.')[2] == 'two') {
            form.value.dataDetailList[rule.field.split('.')[1]].two = value;
        } else if (rule.field.split('.')[2] == 'three') {
            form.value.dataDetailList[rule.field.split('.')[1]].three = value;
        } else {
            form.value.dataDetailList[rule.field.split('.')[1]].four = value;
        }
        callback();
    }
}
const data = reactive({
    form: {
        province: undefined,
        city: undefined,
        prefecture: undefined,
        dataDetailList: [],
    },
    rules: {
        province: [{ required: true, message: '请选择省', trigger: 'change' }],
        city: [{ required: true, message: '请选择市', trigger: 'change' }],
        prefecture: [{ required: true, message: '请选择区（县）', trigger: 'change' }],
        zero: [{ required: false, message: '请输入保留两位小数的值', trigger: 'blur', validator: positive2decimals }],
        one: [{ required: false, message: '请输入保留两位小数的值', trigger: 'blur', validator: positive2decimals }],
        two: [{ required: false, message: '请输入保留两位小数的值', trigger: 'blur', validator: positive2decimals }],
        three: [{ required: false, message: '请输入保留两位小数的值', trigger: 'blur', validator: positive2decimals }],
        four: [{ required: false, message: '请输入保留两位小数的值', trigger: 'blur', validator: positive2decimals }],
    }
})
const { queryParams, form, rules } = toRefs(data)

// 重置表单
function reset() {
    form.value = {
        province: undefined,
        city: undefined,
        prefecture: undefined,
        structureType: undefined,
        intensity: undefined,
        dataDetailList: [],
    }
    proxy.resetForm("destructionRatioRef");
}


/** 查询建筑物易损性数据列表 */
function getList() {
    loading.value = true;
    getAllbuildingVulnerability({ ...route.query }).then(response => {
        dataList.value = response.data;
        loading.value = false;
        spanObj.value = dataMethod(dataList.value, ['province', 'city', 'prefecture']);
    });
}
// 合并列
function objectSpanMethod({ row, column, rowIndex, columnIndex }) {
    //判断合并列
        const _row = spanObj.value[column.property] ? spanObj.value[column.property][rowIndex] : 1;
        const _col = _row > 0 ? 1 : 0;
        return {
            rowspan: _row,
            colspan: _col,
        }
}


// 修改
function handleUpdate(row) {
    reset();
    isUpdate.value = true;
    title.value = "修改房屋破坏比率"
    getDetail(row)
    open.value = true;
}

/** 删除按钮操作 */
function handleDelete(row) {
    isUpdate.value = false;
    getDetail(row)
}

function getDetail(row) {
    const query = {
        province: row.province,
        city: row.city,
        prefecture: row.prefecture,
    }
    getAllbuildingVulnerability(query).then(response => {
        form.value.province = row.province;
        form.value.city = row.city;
        form.value.prefecture = row.prefecture;
        form.value.dataDetailList = response.data;
    })
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs["destructionRatioRef"].validate(valid => {
        if (valid) {
            checkradio();
            if (messageArr.value.length > 0) {
                const msg = messageArr.value.join('<br/><br/>')
                ElMessage({
                    message: msg,
                    type: 'error',
                    dangerouslyUseHTMLString: true,
                })
            } else {
                updatebuildingVulnerability(form.value.dataDetailList).then(response => {
                    proxy.$modal.msgSuccess("修改成功");
                    open.value = false;
                    getList();
                });
            }
        }
    });

}

// 防止精度不准确
function precision(num, precise) {
    return parseFloat(num.toPrecision(precise));
}

// 校验表单项目比例
function checkradio() {
    messageArr.value = [];
    var zero = 0;
    var one = 0;
    var two = 0;
    var three = 0;
    var four = 0;
    var five = 0;
    var six = 0;
    var seven = 0;
    var eight = 0;
    var nine= 0;
    form.value.dataDetailList.forEach(item => {//遍历数据
        if(item.structureType=='0'){
            zero += parseFloat(Number(item.zero)+Number(item.one)+Number(item.two)+Number(item.three)+Number(item.four))
        }else if (item.structureType=='1') {
            one +=  parseFloat(Number(item.zero)+Number(item.one)+Number(item.two)+Number(item.three)+Number(item.four))
        }else if (item.structureType=='2') {
            two +=  parseFloat(Number(item.zero)+Number(item.one)+Number(item.two)+Number(item.three)+Number(item.four))
        }else if (item.structureType=='3') {
            three +=  parseFloat(Number(item.zero)+Number(item.one)+Number(item.two)+Number(item.three)+Number(item.four))
        }else if (item.structureType=='4') {
            four +=  parseFloat(Number(item.zero)+Number(item.one)+Number(item.two)+Number(item.three)+Number(item.four))
        }else if (item.structureType=='5') {
            five +=  parseFloat(Number(item.zero)+Number(item.one)+Number(item.two)+Number(item.three)+Number(item.four))
        }else if (item.structureType=='6') {
            six +=  parseFloat(Number(item.zero)+Number(item.one)+Number(item.two)+Number(item.three)+Number(item.four))
        }else if (item.structureType=='7') {
            seven += parseFloat(Number(item.zero)+Number(item.one)+Number(item.two)+Number(item.three)+Number(item.four))
        }else if (item.structureType=='8') {
            eight +=  parseFloat(Number(item.zero)+Number(item.one)+Number(item.two)+Number(item.three)+Number(item.four))
        }else if (item.structureType=='9') {
            nine +=  parseFloat(Number(item.zero)+Number(item.one)+Number(item.two)+Number(item.three)+Number(item.four))
        }
    })
    if (precision(zero, 3) != 1.00) {
        messageArr.value.push('土木/石木结构破坏比率不为1')
    }
    if (precision(one, 3) != 1.00) {
        messageArr.value.push('砌体结构破坏比率不为1')
    }
    if (precision(two, 3) != 1.00) {
        messageArr.value.push('木结构破坏比率不为1')
    }
    if (precision(three, 3) != 1.00) {
        messageArr.value.push('窑洞破坏比率不为1')
    }
    if (precision(four, 1) != 1.00) {
        messageArr.value.push('钢筋混凝土结构破坏比率不为1')
    }
    if (precision(five, 1) != 1.00) {
        messageArr.value.push('木（竹）结构破坏比率不为1')
    }
    if (precision(six, 1) != 1.00) {
        messageArr.value.push('混杂结构破坏比率不为1')
    }
    if (precision(seven, 1) != 1.00) {
        messageArr.value.push('钢结构破坏比率不为1')
    }
    if (precision(eight, 1) != 1.00) {
        messageArr.value.push('其他破坏比率不为1')
    }
    if (precision(nine, 1) != 1.00) {
        messageArr.value.push('部框架-抗震墙砌体结构破坏不为1')
    }
}

/** 取消按钮 */
function cancel() {
    open.value = false;
    reset();
}

// 模板下载
function importTemplate(name) {
    proxy.download("/fxfzaqbz/data/downloadExcel", {
        fileName: name
    }, name);
};

/** 导出按钮操作 */
function handleExport() {
    proxy.download('/fxfzaqbz/DestoryRate/exportExcel', {
        ...route.query,
    }, '房屋破坏比率.xls')
}

function handleOut() {
    router.push({path: '/assess/populationMap', query: {id: assessId.value}})
}

function handleSave() {
    if(dataList.value[0].one){
        router.push({path:'/assess/populationMap', query: {id: assessId.value}})
    }else{
        ElMessage({
                    message: '该区划下的房屋破坏比率不能为空',
                    type: 'error',
                    dangerouslyUseHTMLString: true,
                })
    }
}

/** 提交上传文件 */
function submitFileForm() {
    proxy.$refs["uploadRef"].submit();
};

/** 打开导入表弹窗 */
function handleImport() {
    upload.title = "导入";
    upload.open = true;
}

/**文件上传前处理 */
function handleFileBeforeUpload(file) {
    proxy.$modal.loading("正在导入文件，请稍候...");
    return true
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
    upload.isUploading = true;
};
// 上传失败
function handleFileUploadError(err) {
    proxy.$modal.closeLoading();
    proxy.$modal.msgError("导入文件失败");
}
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
    upload.open = false;
    upload.isUploading = false;
    proxy.$modal.closeLoading();
    proxy.$refs["uploadRef"].handleRemove(file);
    proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.data + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
    getList();
};

getList();
</script>
  

<style lang="scss" scoped>
:deep(.el-table) td.el-table__cell {
    border-bottom: 1px solid #ebeef5 !important;
    border-right: 1px solid #ebeef5 !important;
}

.el-dialog {
    :deep(.el-table) tr {
        height: 65px !important;
    }

    td.el-table__cell .cell .el-form-item {
        padding-top: 10px;
    }
}
</style>